package  
{
	import flash.geom.Vector3D;
	import starling.core.Starling;
	
	public class BoidColorModifier
	{
		private const COLOR_POWER:Number = 1;
		
		private var mStageWidth:int = 1280;
		private var mStageHeight:int = 720;
		private var mPos:Vector3D = new Vector3D();
		private var mColor:uint = 0;
		private var mEffectRange:Number = 0;
		private var mEffectRangeSquared:Number = 0;
		private var mTmpDist:Vector3D = new Vector3D();
		private var mDistSquared:Number = 0;
		private var mPercent:Number = 0;
		
		private var mR:uint = 0;
		private var mG:uint = 0;
		private var mB:uint = 0;
		private var mTargetR:uint = 0;
		private var mTargetG:uint = 0;
		private var mTargetB:uint = 0;
		
		public function BoidColorModifier(aPos:Vector3D, aColor:uint) 
		{
			mStageWidth = Starling.current.stage.stageWidth;
			mStageHeight = Starling.current.stage.stageHeight;
			
			mEffectRange = mStageHeight / 6;
			mEffectRangeSquared = mEffectRange * mEffectRange;
			mPos.copyFrom(aPos);
			mColor = aColor;
			mTargetR = (mColor >> 16) & 0xFF;
			mTargetG = (mColor >> 8) & 0xFF;
			mTargetB = mColor & 0xFF;
		}
		
		public function ComputeBoid(aBoid:Boid):void
		{
			mTmpDist.x = aBoid.mPos.x - mPos.x;
			mTmpDist.y = aBoid.mPos.y - mPos.y;
			mTmpDist.z = aBoid.mPos.z - mPos.z
			
			mPercent = Math.abs(mTmpDist.lengthSquared / mEffectRangeSquared);
			
			if (mPercent < 1)
			{
				mPercent = 1 - mPercent;
				
				//Extract color channels from the boid
				mR = (aBoid.mColor >> 16) & 0xFF;
				mG = (aBoid.mColor >> 8) & 0xFF;
				mB = aBoid.mColor & 0xFF;
				
				//Calculate color power to add based on distance and target color
				mR += COLOR_POWER * mPercent * mTargetR;
				mG += COLOR_POWER * mPercent * mTargetG;
				mB += COLOR_POWER * mPercent * mTargetB;
				
				//Apply the new color to the boid
				mR = mR > 0xFF ? 0xFF : mR;
				mG = mG > 0xFF ? 0xFF : mG;
				mB = mB > 0xFF ? 0xFF : mB;
				
				aBoid.mColor = mR << 16 | mG << 8 | mB;
			}
		}
	}
}